package cn.yunhe.controller;

import cn.yunhe.entity.ShoppingCart;
import cn.yunhe.entity.ShoppingCartItem;
import cn.yunhe.entity.User;
import cn.yunhe.service.CartService;
import cn.yunhe.service.ProductService;
import cn.yunhe.service.UserService;
import cn.yunhe.util.ShoppingCartUtil;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private CartService cartService = new CartService();
    private ProductService productService = new ProductService();
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String methodName = request.getParameter("method");

        try {
            Method method;
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //检查库存是否足够
    public StringBuffer validateBookStoreNumber(HttpServletRequest request) {

        StringBuffer errors = new StringBuffer("");
        ShoppingCart cart = ShoppingCartUtil.getShoppingCart(request);

        for (ShoppingCartItem sci : cart.getItems()) {
            int quantity = sci.getQuantity();
            int storeNumber = productService.getProduct(sci.getProduct().getProductid()).getStore();

            if (quantity > storeNumber) {
                errors.append(sci.getProduct().getProductname() + "库存不足<br>");
            }
        }

        return errors;
    }


    //验证表单域是否符合基本的规则: 是否为空.
    public StringBuffer validateFormField(String username, String accountId) {
        StringBuffer errors = new StringBuffer("");

        if (username == null || username.trim().equals("")) {
            errors.append("用户名不能为空<br>");
        }


        return errors;
    }

    protected void updateItemQuantity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String productidStr = request.getParameter("productid");
        String quantityStr = request.getParameter("quantity");
        ShoppingCart sc = ShoppingCartUtil.getShoppingCart(request);
        int productid = -1;
        int quantity = -1;
        try {
            productid = Integer.parseInt(productidStr);
            quantity = Integer.parseInt(quantityStr);
        } catch (Exception e) {
        }
        if (productid > 0 && quantity > 0) {
            cartService.updateItemQuantity(sc, productid, quantity);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("productNumber", sc.getProductNumber());
        result.put("totalMoney", sc.getTotalMoney());
        Gson gson = new Gson();
        String jsonStr = gson.toJson(result);
        response.setContentType("text/javascript");
        response.getWriter().print(jsonStr);
    }
    protected void forwardPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = request.getParameter("page");
        request.getRequestDispatcher("" + page + ".jsp").forward(request, response);
    }
    //清空购物车跳转到空购物车页面
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ShoppingCart sc = ShoppingCartUtil.getShoppingCart(request);
        cartService.clearShoppingCart(sc);
        request.getRequestDispatcher("emptycart.jsp").forward(request, response);
    }

    //根据商品id移除购物车的某种商品,判断购物车是否为空,空的话跳转页面
    protected void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("productid");
        int productid = -1;
        try {
            productid = Integer.parseInt(idStr);
        } catch (Exception e) {
        }
        ShoppingCart sc = ShoppingCartUtil.getShoppingCart(request);
        cartService.removeItemFromShoppingCart(sc, productid);
        if (sc.isEmpty()) {
            request.getRequestDispatcher("emptycart.jsp").forward(request, response);
            return;
        }
    }

    protected void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr=request.getParameter("productid");
        int productid = -1;
        boolean flag = false;
        try{
            productid=Integer.parseInt(idStr);
        }catch (Exception e) {}
        if(productid>0){
            ShoppingCart sc=ShoppingCartUtil.getShoppingCart(request);
            flag=cartService.addToCart(productid,sc);
        }
        if(flag){
            request.getRequestDispatcher("product-list.jsp").forward(request, response);
            return;
        }
    }

}
